﻿CREATE PROCEDURE [dbo].[yaf_pmessage_save](
                @FromUserID INT,
                @ToUserID   INT,
                @Subject    NVARCHAR(100),
                @Body       NTEXT,
                @Flags      INT)
AS
    BEGIN
        DECLARE  @PMessageID INT
        DECLARE  @UserID INT
        INSERT INTO yaf_PMessage
                   (FromUserID,
                    Created,
                    Subject,
                    Body,
                    Flags)
        VALUES     (@FromUserID,
                    Getdate(),
                    @Subject,
                    @Body,
                    @Flags)
        SET @PMessageID = Scope_identity()
        IF (@ToUserID = 0)
        BEGIN
            INSERT INTO yaf_UserPMessage
                       (UserID,
                        PMessageID,
                        IsRead)
            SELECT   a.UserID,
                     @PMessageID,
                     0
            FROM     yaf_User a
                     JOIN yaf_UserGroup b
                       ON b.UserID = a.UserID
                     JOIN yaf_Group c
                       ON c.GroupID = b.GroupID
            WHERE    (c.Flags & 2) = 0
            AND c.BoardID = (SELECT BoardID
                             FROM   yaf_User x
                             WHERE  x.UserID = @FromUserID)
            AND a.UserID <> @FromUserID
            GROUP BY a.UserID
        END
        ELSE
        BEGIN
            INSERT INTO yaf_UserPMessage
                       (UserID,
                        PMessageID,
                        IsRead)
            VALUES     (@ToUserID,
                        @PMessageID,
                        0)
        END
    END


